'''
文件对话框： QFileDialog
'''

import sys

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class QFileDialogDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('输入文件对话框')

        layout = QVBoxLayout()
        self.btn0 = QPushButton('loading image files')
        self.btn0.clicked.connect(self.LoadImage)
        self.imageLabel = QLabel()
        layout.addWidget(self.btn0)
        layout.addWidget(self.imageLabel)

        self.btn1 = QPushButton('loading text files')
        self.btn1.clicked.connect(self.LoadText)
        self.contents = QTextEdit()
        layout.addWidget(self.btn1)
        layout.addWidget(self.contents)

        self.setLayout(layout)

    def LoadImage(self):

        fname, _ =QFileDialog.getOpenFileName(self, '打开文件', '.', '图像文件(*.jpg *.png) ')
        self.imageLabel.setPixmap(QPixmap(fname))

    def LoadText(self):
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setFilter(QDir.Files)

        if dialog.exec_():
            filenams = dialog.selectedFiles()
            f = open(filenams[0],encoding='utf-8', mode='r')
            with f:
                data = f.read()
                self.contents.setText(data)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = QFileDialogDemo()
    ex.show()
    sys.exit(app.exec_())